﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
using MedicalAssistant.core.dao;

namespace MedicalAssistant.core.dao.binary
{
    abstract class BinGenericDAO<T,ID> : GenericDAO<T,ID>
    {
        public abstract T FindById(ID id);

        public List<T> GetAll()
        {
            IFormatter formatter = new BinaryFormatter();
            string path = GetBinPath();
            Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            List<T> all = (List<T>)formatter.Deserialize(stream);
            stream.Close();

            return all;
        }


        public abstract T Save(T entity);

        public abstract void Delete(T entity);

        protected void MakePersistent(List<T> all)
        {
            IFormatter formatter = new BinaryFormatter();
            string path = GetBinPath();
            Stream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, all);
            stream.Close();
        }

        protected abstract string GetBinPath();

    }
}